<template>
  <div>
    <el-row>
      <el-col>
        <my-form
          :formOptions="findFormOptions"
          :isInline="true"
          :isSearch="true"
          @sureSubmit="findTableData"
        >
          <template #bottom_button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              type="primary"
              @click="reset"
              >重置</el-button
            >
          </template>
        </my-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end">
      <el-col :span="2"  >
        <el-popconfirm
          confirm-button-text="审核通过"
          cancel-button-text="审核不通过"
          confirm-button-type="success"
          cancel-button-type="danger"
          @confirm="check_T"
          @cancel="check_F"
          icon="el-icon-info"
          icon-color="red"
          title="请选择操作"
        >
          <el-button
            slot="reference"
            icon="el-icon-coordinate"
            type="primary"
            size="mini"
            v-if="nowRoot != '教师'"
            >批量审核</el-button
          >
        </el-popconfirm>
      </el-col>
      <el-col :span="10">
        <el-button
          size="mini"
          @click="add"
          icon="el-icon-circle-plus"
          type="primary"
          v-if="nowRoot === '教师'"
          >新增</el-button
        >

        <el-upload
          class="upload-demo"
          ref="excelUpload"
          action="http://localhost:8080/api/project/zUploadExcel"
          :before-upload="onBeforeUpload"
          :on-success="uploadSuccess"
          :show-file-list="false"
        >
          <el-button icon="el-icon-upload" type="primary" size="mini" v-if="nowRoot === '教师'">导入数据表格</el-button>
        </el-upload>
         <el-button size="mini" icon="el-icon-download" type="primary" @click="downloadExample"
          >下载导入样例xlsx表格</el-button
        >
        <el-button size="mini" icon="el-icon-download" type="primary" @click="downloadExcel"
          >导出表格</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <my-table
          :hasBorder="true"
          :hasIndex="true"
          :hasPagination="true"
          :hasStripe="true"
          :hasSelection="true"
          :tableColumnOptions="tableColumnOptions"
          :tableData="tableData"
          @selectionChange="selectionChange"
        >
          <template #zbegin="{ data }">
            {{ (data.zbegin + "").slice(0, 10) }}
          </template>
          <template #zstart="{ data }">
            {{ (data.zstart + "").slice(0, 10) }}
          </template>
          <template #zend="{ data }">
            {{ (data.zend + "").slice(0, 10) }}
          </template>
          <template #zsstate="{ data }">
            {{
              data.zsstate == "-1"
                ? "未通过"
                : data.zsstate == "0"
                ? "未审核"
                : data.zsstate == "1"
                ? "院级通过"
                : "校级通过"
            }}
          </template>
          <template #operation="{ data }">
            <el-button type="text" @click="look(data)">查看</el-button>
            <el-button
              type="text"
              @click="update(data)"
              v-if="nowRoot === '教师'"
              >编辑</el-button
            >

            <el-button
              type="text"
              @click="remove(data)"
              v-if="nowRoot === '教师'"
              >删除</el-button
            >
          </template>
        </my-table>
      </el-col>
    </el-row>
    <my-dialog :dialogVisible.sync="infoDialog" :title="infoTitle">
      <template #content>
        <my-form
          :form="isAddInfo ? copyForm : form"
          :formOptions="infoFormOptions"
           
          :rules="infoRules"
          @sureSubmit="infoFormSubmit"
          ref="infoForm"
        >
          <template #zadmin="{ data }">
            <el-autocomplete
              v-model="user1"
              :fetch-suggestions="querySearch"
              style="width: 192px"
              placeholder="请输入内容"
              @select="handleSelect_person"
            ></el-autocomplete>
          </template>
          <template #zcategorya>
            <el-select
              v-model="test1"
              placeholder="请选择"
              @change="handleLevel1"
              style="width:207px"
            >
              <el-option
                v-for="item in level1"
                :key="item.model"
                :label="item.label"
                :value="item.model"
              >
              </el-option>
            </el-select>
          </template>
          <template #zgrade>
            <el-select
              v-model="test2"
              placeholder="请选择"
              @change="handleLevel2"
              style="width:217px"
            >
              <el-option
                v-for="item in level2"
                :key="item.model"
                :label="item.label"
                :value="item.model"
              >
              </el-option>
            </el-select>
          </template>
          <template #bottom_button>
            <el-upload
              class="upload-files"
              ref="filesUpload"
              action="http://localhost:8080/api/SciThesis/uploadFile"
              :before-upload="onBeforeUploadFile"
              :data="uploadmsg"
              :multiple="true"
              :limit="1"
              :show-file-list="true"
              :auto-upload="false"
            >
              <el-button type="success"icon="el-icon-upload" size="mini"
                >上传附件(仅支持一个文件)</el-button
              >
            </el-upload>
          </template>
        </my-form>
      </template>
    </my-dialog>
    <my-dialog :dialogVisible.sync="lookDialog">
      <template #content>
        <my-description :border="false" :list="list">
          <template #bottom>
            下载附件
            <el-link
              type="primary"
              v-for="(item, index) in files"
              :key="item"
              @click="downLoadFiles(item)"
              >{{ item }}</el-link
            >
          </template>
        </my-description>
      </template>
    </my-dialog>
  </div>
</template>

<script>
import  {projectCate,getLabelByModel,contractStatus,projectGrade,getModelByLabel}  from "@/utils/metaInfo.js"
import myForm from "@/components/myForm.vue";
import myTable from "@/components/myTable.vue";
import myDialog from "@/components/myDialog.vue";
import { A_getUserList } from "@/utils/aboutUsers";
import myDescription from "@/components/myDescription.vue";
import {
  A_findTableData,
  A_tableData,
  A_add,
  A_update,
  A_remove,
  A_check_T,
  A_check_F,
  A_downLoadExcel,
  A_getFile,
  A_getLevel1,
  A_getLevel2,
  A_downLoadExample,
} from "@/api/resultMange/researchProjects/verticalProject";
import {
  E_beforeUpload,
  E_uploadSuccess,
  E_downloadExcel,
} from "@/utils/aboutExcel";
import cloneDeep from "lodash/cloneDeep";
import { A_downLoadFile, A_showFile, A_getKey } from "@/utils/aboutFile";

import { mapState } from "vuex";
export default {
  name: "verticalProject",
  inject: ["reload"],
  data() {
    return {
      findFormOptions: [{ type: "input", label: "项目名称", model: "zname" }],
      tableColumnOptions: [
        {
          label: "项目名称",
          prop: "zname",
        },
        {
          label: "项目编号",
          prop: "znumber",
        },
        {
          label: "负责人编号",
          prop: "zadmin",
        },
        {
          label: "负责人姓名",
          prop: "name",
        },
        {
          label: "学科门类",
          prop: "zcategory",
        },
        {
          label: "项目分类",
          prop: "zcategorya",
        },
        {
          label: "项目成员",
          prop: "znum",
          width: "120",
        },
        {
          label: "项目状态",
          prop: "zstate",
        },
        {
          label: "项目金额（万元）",
          prop: "zamount",
        },
        {
          isSlot: true,
          slotName: "zbegin",
          label: "项目时间",
          prop: "zbegin",
        },
        {
          isSlot: true,
          slotName: "zstart",
          label: "立项时间",
          prop: "zstart",
        },
        {
          isSlot: true,
          slotName: "zend",
          label: "结项时间",
          prop: "zend",
        },
        {
          label: "项目级别",
          prop: "zgrade",
        },
        {
          label: "学科分类",
          prop: "zscicategory",
        },
        {
          label: "结项等级",
          prop: "zendlevel",
        },
        {
          label: "结项分数",
          prop: "zendscore",
        },
        {
          label: "项目分值",
          prop: "zscore",
        },
        {
          label: "其他内容",
          prop: "zdescribe",
        },
        {
          isSlot: true,
          slotName: "zsstate",
          label: "审核状态",
          prop: "zsstate",
        },
        {
          label: "操作",
          width: "180",
          isSlot: true,
          slotName: "operation",
          fixed: "right",
        },
      ],
      tableData: [],
      infoDialog: false,
      infoTitle: "编辑操作",
      isAddInfo: false,
      lookDialog: false,
      form: {},
      copyForm: {},
      infoFormOptions: [
         {
          type: "radio",
          label: "学科门类",
          model: "zcategory",
          width:500,
          options: projectCate
        },
        {
          type: "input",
          label: "项目名称",
          model: "zname",
        },
        {
          type: "input",
          label: "项目编号",
          model: "znumber",
        },
       
        {
          type: "slot",
          slotName: "zcategorya",
          label: "项目分类",
          model: "zcategorya",
        },
        {
          type: "slot",
          slotName: "zgrade",
          label: "项目级别",
          model: "zgrade",
        },
        
        {
          type: "slot",
          slotName: "zadmin",
          label: "负责人编号",
          model: "zadmin",
        },
        {
          type: "input",
          label: "项目成员",
          model: "znum",
        },
        {
          type: "radio",
          label: "学科分类",
          model: "zscicategory",
          width:500,
          options: projectCate
        },
        {
          type: "radio",
          label: "项目状态",
          model: "zstate",
          width:500,
          options:contractStatus
        },
        {
          type: "input",
          label: "项目金额（万元）",
          model: "zamount",
        },
        {
          type: "date",
          label: "项目时间",
          model: "zbegin",
        },
        {
          type: "date",
          label: "立项时间",
          model: "zstart",
        },
        {
          type: "date",
          label: "结项时间",
          model: "zend",
        },

        {
          type: "radio",
          label: "结项等级",
          model: "zendlevel",
          options: projectGrade,
        },
        {
          type: "textarea",
          label: "其他内容",
          model: "zdescribe",
          width:500
        },
      ],
      infoRules: {
        zcategory: [{ required: true, message: "请选择学科门类" }],
        zcategorya: [{ required: false, message: "请选择项目分类" }],
        zname: [{ required: true, message: "请输入项目名称" }],
        znumber: [{ required: true, message: "请输入项目编号" }],
        zadmin: [{ required: true, message: "请输入负责人编号" }],
        znum: [{ required: true, message: "请输入项目成员" }],
        zstate: [{ required: true, message: "请选择项目状态" }],
        zamount: [{ required: true, message: "请输入项目金额（万元）" }],
        zbegin: [{ required: true, message: "请选择项目时间" }],
        zstart: [{ required: true, message: "请选择立项时间" }],
        zend: [{ required: true, message: "请选择结项时间" }],
        zgrade: [{ required: false, message: "请选择项目级别" }],
        zsstate: [{ required: true, message: "请选择审核状态" }],
        zscicategory: [{ required: true, message: "请选择学科分类" }],
        zendlevel: [{ required: false, message: "请选择结项等级" }],
        zdescribe: [{ required: true, message: "请输入其他内容" }],
      },
      multipleSelection: [],
      uploadmsg: {},
      slideArr: [],
      files: [],
      level1: [],
      level2: [],
      test1: "",
      test2: "",
      fileKey: 0,
      user1: "",
      user_list: null,
    };
  },
  components: {
    myForm,
    myTable,
    myDialog,
    myDescription,
  },
  created() {
    this.getTableData();
    this.getLevel1();
  },
  methods: {
    async getUserList() {
      let result = await A_getUserList();
      result.forEach((item) => {
        const value=item.userId+' : '+item.userName
        item.value=value
      });
      this.user_list=result
    },
    async findTableData(data) {
      let result = await A_findTableData(data);
      this.tableData = cloneDeep(result.data);
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    async getTableData() {
      let result = await A_tableData({});
      console.log("zcategorya",result)
      


      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
        

        this.tableData.forEach(async item=>{
          item.zcategory = getLabelByModel(item.zcategory,projectCate)
          item.zstate =  getLabelByModel(item.zstate,contractStatus)
          item.zendlevel =  getLabelByModel(item.zendlevel,projectGrade)
          
          let level2 =  await A_getLevelByGrade(item.znatsciKey,item.zcategorya);
          var obj = []
          level2.data.forEach((item) => {
              obj.push({
              model: item.znatsciLevel,
              label: item.znatsciLevel
            });
          });
          this.level2 = obj;
          item.zcategorya =  getLabelByModel(parseInt(item.zcategorya),this.level1)
          item.zgrade =  getLabelByModel(parseInt(item.zgrade),obj)
        })      

      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    async reset() {
      let result = await A_tableData({});
     
      if (result.code === 1) {
        this.tableData = cloneDeep(result.data);
      } else {
        this.$message({ type: "error", message: "信息获取失败" });
      }
    },
    selectionChange(data) {
      this.multipleSelection = cloneDeep(data);
    },
    async look(data) {
      this.form = cloneDeep(data);
      this.lookDialog = true;
      const { zkey } = data;
      let res = await A_getFile(zkey);
      if (res.code === 1) {
        this.files = res.data;
      } else {
        this.$message({ type: "error", message: "出错啦" });
      }
    },
    add() {
      this.isAddInfo = true;
      this.infoDialog = true;
      this.getUserList();
    },
    update(data) {
      this.isAddInfo = false;
      this.infoDialog = true;
      this.form = cloneDeep(data);
      this.getUserList();
    },
    remove(data) {
      this.$confirm("你确定要删除该数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { zkey } = data;
          let res = await A_remove(zkey);
          if (res.code === 1) {
            this.$message({ type: "success", message: res.data });
            this.reload();
          } else {
            this.$message({ type: "error", message: res.msg });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async check_T() {
      if (this.multipleSelection.length > 0) {
        let res = await A_check_T(this.downloadExcelData);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        this.$message.warning("请选择数据");
      }
    },
    async check_F() {
      if (this.multipleSelection.length > 0) {
        let res = await A_check_F(this.downloadExcelData);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        this.$message.warning("请选择数据");
      }
    },
    async infoFormSubmit(data) {
      data.zcategory = getModelByLabel(data.zcategory,projectCate)
      data.zstate =  getModelByLabel(data.zstate,contractStatus)
      data.zendlevel =  getModelByLabel(data.zendlevel,projectGrade)
      // data.zcategorya =  getModelByLabel(parseInt(data.zcategorya),this.level1)
      // data.zgrade =  getModelByLabel(parseInt(data.zgrade),this.level2)

      if (this.isAddInfo) { 
        let res = await A_add(data);
        if (res.code === 1) {
          await this.getFileKey();
          await this.$refs.filesUpload.submit();
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        let res = await A_update(data);
        if (res.code === 1) {
          await this.$refs.filesUpload.submit();
          this.$message({ type: "success", message: res.data });

          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      }
    },
    onBeforeUpload(file) {
      return E_beforeUpload(file);
    },
    uploadSuccess(res, file, flieist) {
      E_uploadSuccess(res);
      this.reload();
    },
    downloadExcel() {
      if (this.multipleSelection.length > 0) {
        E_downloadExcel(this.downloadExcelData).then(
          () => {
            A_downLoadExcel().then(
              (res) => {
                const url = window.URL.createObjectURL(new Blob([res]));
                const link = document.createElement("a");
                link.href = url;
                link.setAttribute("download", "科研平台.xls");
                document.body.appendChild(link);
                link.click();
              },
              () => {
                this.$message({ type: "error", message: "出错了" });
              }
            );
          },
          () => {
            this.$message({ type: "error", message: "出错了" });
          }
        );
      } else {
        this.$message({ type: "warning", message: "请选择要导出的数据" });
      }
    },
      downloadExample() {
      A_downLoadExample().then(
        (res) => {
          const url = window.URL.createObjectURL(new Blob([res]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "导入数据样例表.xls");
          document.body.appendChild(link);
          link.click();
        },
        () => {
          this.$message({ type: "error", message: "出错了" });
        }
      );
    },
    async onBeforeUploadFile(file) {
      if (this.isAddInfo) {
        this.uploadmsg = {
          articalTcatogory: file.name,
          articalCatogory: 2,
          articalId: this.fileKey,
        };
      } else {
        const { zkey } = this.form;
        this.uploadmsg = {
          articalTcatogory: file.name,
          articalCatogory: 2,
          articalId: zkey,
        };
      }
    },
    async downLoadFiles(file) {
      const { zkey } = this.form;
      let result = await A_downLoadFile(2, zkey, file);
      A_showFile(file, result);
    },
    async getLevel1() {
      let result = await A_getLevel1();
      var obj = []
      result.data.forEach((item) => {
          obj.push({
            model: item.znatsciCategory,
            label: item.znatsciCategory
          });
     });
     this.level1 = obj;
    },
    async handleLevel1(item) {
      this.$refs.infoForm.form.zcategorya = item;
      let res = await A_getLevel2(item);

      var obj = []
      res.data.forEach((item) => {
          obj.push({
            model: item.znatsciLevel,
            label: item.znatsciLevel
          });
     });
      this.level2 = obj;
    },
    handleLevel2(item) {
      this.$refs.infoForm.form.zgrade = item;

    },
    async getFileKey() {
      let result = await A_getKey(2);
      this.fileKey = result.data;
    },
    querySearch(queryString, cb) {
      var user_list = this.user_list;
      var results = queryString
        ? user_list.filter(this.createFilter(queryString))
        : user_list;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (user_list) => {
        return (
          user_list.userName.indexOf(queryString) === 0
        );
      };
    },
    handleSelect_person(item) {
      this.$refs.infoForm.form.zadmin = item.userId;
    },
  },
  computed: {
    ...mapState("myInfo", ["nowRoot"]),
    downloadExcelData() {
      let arr = [];
      this.multipleSelection.forEach((item) => {
        arr.push(item.zkey);
      });
      return arr;
    },
    list() {
      const {
        zcategory,
        zcategorya,
        zname,
        znumber,
        zadmin,
        znum,
        zstate,
        zamount,
        zbegin,
        zstart,
        zend,
        zgrade,
        zscore,
        zscicategory,
        zendlevel,
        zsstate,
        zendscore,
        zdescribe,
      } = this.form;
      return [
        {
          label: "项目名称",
          value: zname,
        },
        {
          label: "项目编号",
          value: znumber,
        },
        {
          label: "学科分类",
          value: zscicategory,
        },
        {
          label: "项目类别",
          value: zcategory,
        },
        {
          label: "项目分类",
          value: zcategorya,
        },
        {
          label: "项目负责人编号",
          value: zadmin,
        },
        {
          label: "项目成员",
          value: znum,
        },
        {
          label: "项目状态",
          value: zstate,
        },
        {
          label: "项目金额（万元）",
          value: zamount,
        },
        {
          label: "项目时间",
          value: (zbegin + "").slice(0, 10),
        },
        {
          label: "立项时间",
          value: (zstart + "").slice(0, 10),
        },
        {
          label: "结项时间",
          value: (zend + "").slice(0, 10),
        },
        {
          label: "项目级别",
          value: zgrade,
        },
        {
          label: "结项等级",
          value: zendlevel,
        },
        {
          label: "科研分值",
          value: zscore,
        },
        {
          label: "结项分数",
          value: zendscore,
        },
        {
          label: "其他内容",
          value: zdescribe,
        },
        {
          label: "审核状态",
          value: zsstate,
        },
        {
          label: "项目分值",
          prop: zscore,
        }
      ];
    },
  },
};
</script>

<style scoped>
.upload-demo {
  display: inline-block;
  margin: 0 3px;
}
</style>